﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace BF
{
    public class AESSetting : ScriptableObject
    {
        public string PREFIX = "__BF";
        public string KEY = "";
        public string IV = "";


        private const string SETTING_PATH = "Assets/__BF/Resources/AES/";
        private const string SETTING_NAME = "AESKey";

        private static readonly string SETTING_FILE_PATH =
            Path.Combine(SETTING_PATH, SETTING_NAME + ".asset");


        public static AESSetting GetInstance()
        {
            AESSetting setting = null;

            setting = Resources.Load<AESSetting>("AES/AESKey");

#if UNITY_EDITOR
            if (setting == null)
            {
                setting = AssetDatabase.LoadAssetAtPath<AESSetting>(SETTING_FILE_PATH);
            }
            if (setting == null)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(SETTING_PATH);
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                setting = CreateInstance<AESSetting>();
                setting.PREFIX = "__BF";
                setting.KEY = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                setting.IV = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                AssetDatabase.CreateAsset(setting, SETTING_FILE_PATH);
                AssetDatabase.Refresh();
            }
#endif

            return setting;
        }

#if UNITY_EDITOR
        [MenuItem("BF/AES/Edit AESKey", false, 0)]
        public static void EditSetting()
        {
            Selection.activeObject = GetInstance();
        }

        [MenuItem("BF/AES/Random AESKEY", false, 0)]
        public static void RandomSetting()
        {
            AESSetting setting = GetInstance();
            Selection.activeObject = setting;
            setting.PREFIX = "__BF";
            setting.KEY = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
            setting.IV = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
        }
#endif
    }
}